<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Drag2Share</title>
</head>
<body>
  <div id="drop_zone">
    <select id="fileSelect"></select>
    <button onclick="handleView();">View</button>
    <button onclick="handleDownload();">Download</button>
    <button onclick="updateSelector();">Update</button>
    <table>
      <tr>
        <td id="drop_text">Drop File(s) Here</td>
      </tr>
    </table>
  </div>
</body>
<script type="text/javascript">
	function handleFileSelect(evt) {
		evt.stopPropagation();
		evt.preventDefault();
		var files = evt.dataTransfer.files; // FileList object
		var finished;
		for ( var i = 0, file; file = files[i]; i++) {
			var request = new XMLHttpRequest();
			request.open('POST', '/files/' + file.name);
			request.onreadystatechange = function() {
				if (!files[i + 1] && !finished) {
					window.alert("Upload Completed");
					finished = true;
					updateSelector();
				}
			}
			request.send(file);
		}
		document.getElementById('drop_zone').className = "";
	}

	function handleDragOver(evt) {
		evt.stopPropagation();
		evt.preventDefault();
		document.getElementById('drop_zone').className = "over";
	}

	function handleLeave(evt) {
		evt.stopPropagation();
		evt.preventDefault();
		document.getElementById('drop_zone').className = "";
	}

	function handleView() {
		var select = document.getElementById("fileSelect");
		window.open("files/" + select.options[select.selectedIndex].value);
	}

	function handleDownload() {
		var select = document.getElementById("fileSelect");
		window.location += "files/"
				+ select.options[select.selectedIndex].value + "?download";
	}

	function updateSelector() {
		var select = document.getElementById("fileSelect");
		while (select.options.length > 0) {
			select.remove(0);
		}
		var request = new XMLHttpRequest();
		request.open('GET', '/info', false);
		request.send(null);
		var json = eval(request.responseText);
		for ( var i = 0; i < json.length; i++)
			AddSelectOption(select, json[i], json[i], true);
		select.selectedIndex = 0;
	}

	function AddSelectOption(selectObj, text, value, isSelected) {
		if (selectObj != null && selectObj.options != null)
			selectObj.options[selectObj.options.length] = new Option(text,
					value, false, isSelected);
	}

	// Setup the dnd listeners.
	var dropZone = document.getElementById('drop_zone');
	dropZone.addEventListener('dragover', handleDragOver, false);
	dropZone.addEventListener('dragleave', handleLeave, false);
	dropZone.addEventListener('drop', handleFileSelect, false);

	// Initialize file selector
	updateSelector();
</script>
<style type="text/css">
#drop_zone {
  width: 100%;
  height: 100%;
}

#drop_zone.over {
  background: gray;
}

#drop_text {
  text-align: center;
  vertical-align: middle;
}

html,body,table {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden;
}
</style>
</html>